package fr.univ.surveyonline.dispatcher;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.univ.surveyonline.datastore.PMF;
import fr.univ.surveyonline.language.Language;
import fr.univ.surveyonline.model.Survey;
import fr.univ.surveyonline.model.User;
import fr.univ.surveyonline.model.allEnum.Role;

public class DeleteServlet extends HttpServlet	{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
			
			String langue = "FR";
			for (Cookie c : req.getCookies()) {
				if (c.getName().equals("langue")) {
					langue = c.getValue(); 
					break;
				}
			}
			
			User u = (User) req.getSession().getAttribute("user");
			if ((u == null)||(u.getRole() == Role.MEMBRE)) {
				req.setAttribute("message", Language.getWord("unq_sondeurs",langue));
	    		try {
					req.getRequestDispatcher("unaccessible.jsp").forward(req, resp);
					return;
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}
			
			String fromScreen = req.getServletPath();
			if (fromScreen.equals("/delete")) {
				long id = 0;
				try {
					id = Long.valueOf(req.getParameter("survey"));
				} catch (Exception e) {
					req.setAttribute("message", Language.getWord("unq_sondeur_cree",langue));
		    		try {
						req.getRequestDispatcher("unaccessible.jsp").forward(req, resp);
						return;
					} catch (ServletException e2) {
						e2.printStackTrace();
					}
				}
				
				Survey s = (Survey) PMF.getElementById(Survey.class, id);
				
				PMF.delete(s);
				
			}
			RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
			try {
				rd.forward(req, resp);
			} catch (ServletException e) {
				e.printStackTrace();
			}
		}
		
		public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
			doPost(req, resp);
		}

}
